Skip to content

MCP Bridge (ctxce) + Optional Auth: single MCP server (HTTP/stdio) for Indexer & Memory, VS Code auto‑wiring, backend auth endpoints#48

Merged
m1rl0k merged 58 commits intoContext-Engine-AI:testfrom
voarsh2:cli-fascade
Dec 13, 2025
Merged

MCP Bridge (ctxce) + Optional Auth: single MCP server (HTTP/stdio) for Indexer & Memory, VS Code auto‑wiring, backend auth endpoints#48
m1rl0k merged 58 commits intoContext-Engine-AI:testfrom
voarsh2:cli-fascade

Conversation

@voarsh2
Copy link
Contributor

@voarsh2 voarsh2 commented Dec 8, 2025

Summary

This PR introduces a consolidated MCP bridge CLI (“ctxce”) and opt‑in backend authentication for the Context Engine stack. The bridge exposes a single MCP server over HTTP or stdio that proxies to the Indexer and Memory services, centralizes per‑session defaults, and adds resiliency. The VS Code extension gains auto‑wiring for the HTTP bridge, unified MCP config writing, and a guided sign‑in flow. Backend services provide lightweight auth endpoints (SQLite‑backed) with optional collection ACL enforcement. Behavior remains unchanged unless auth or ACL is enabled.

Motivation

  • Reduce IDE configuration friction: one MCP server instead of separate indexer/memory entries and transports.
  • Centralize session defaults (collection, mode, under, language) to avoid repetitive knob passing in agent workflows.
  • Provide a simple, opt‑in auth model for shared deployments (session TTLs, token/password login) ahead of org/user features.
  • Improve reliability of tool calls under transient errors; align extension workflows with the bridge.

What’s Included

1) MCP bridge CLI (Node 18+)

  • New package: ctx-mcp-bridge/ published as @context-engine-bridge/context-engine-mcp-bridge.
  • Commands:
    • ctxce mcp-serve – stdio MCP bridge.
    • ctxce mcp-http-serve – HTTP MCP bridge (default http://127.0.0.1:<port>/mcp).
    • ctxce auth <login|status|logout> – helper commands for token/password flows.
  • Bridge features:
    • Proxies tools/list and tools/call; injects set_session_defaults (session, collection, mode, under, language).
    • Resiliency: configurable timeouts, transient‑error retries, and session re‑initialization when remote sessions expire.
    • Optional debug logging (CTXCE_DEBUG_LOG); exit when stdin closes (CTXCE_EXIT_ON_STDIN_CLOSE=1).
    • Path remapping for search tool results to workspace‑relative paths (toggle via CTXCE_BRIDGE_MAP_PATHS).

2) Optional backend auth (OFF by default)

  • New module: scripts/auth_backend.py (SQLite users/sessions, PBKDF2 password hashing, sliding TTL).
  • Upload service endpoints:
    • GET /auth/status – enabled, has_users, TTL.
    • POST /auth/login – token flow (client/workspace), gated by CTXCE_AUTH_SHARED_TOKEN or CTXCE_AUTH_ALLOW_OPEN_TOKEN_LOGIN=1.
    • POST /auth/login/password – username/password flow.
    • POST /auth/users – bootstrap first user; subsequent users require X-Admin-Token (from CTXCE_AUTH_ADMIN_TOKEN).
  • Admin UI (served by upload service):
    • /admin with bootstrap, login, ACL pages.
    • Grants/revokes collection access; sets cookie ctxce_session for admin flows.
  • Auth registry integration:
    • Health check syncs Qdrant collections into the auth DB (if enabled).
    • Optional ACL enforcement toggles (CTXCE_MCP_ACL_ENFORCE, CTXCE_ACL_ALLOW_ALL).

3) Indexer/Memory MCP auth enforcement + session defaults

  • Indexer (scripts/mcp_indexer_server.py):
    • Optional session enforcement on protected tools when auth is enabled.
    • set_session_defaults supports collection, mode, under, language; empty strings explicitly unset sticky defaults.
    • repo_search resolves defaults from per‑connection/session scopes, token defaults, and env fallback.
    • Tolerates bridges that omit the MCP session header during handshake.
  • Memory (scripts/mcp_memory_server.py):
    • Optional session enforcement on memory.* tools (find, store) when auth is enabled.
    • HNSW index parameters set on collection creation for better recall at scale.
    • Fastembed model cache and lazy warmups reduce cold‑start latency.

4) Upload clients: session propagation + error handling

  • scripts/remote_upload_client.py and scripts/standalone_upload_client.py:
    • Include session id with uploads (resolved from env or ~/.ctxce/auth.json).
    • Stat caches avoid re‑hashing unchanged files during --watch.
    • SimpleHashCache fixes reduce O(N²) cache churn on Windows watch runs.
    • Explicit 401 handling: returns UNAUTHORIZED with guidance (“log in with ctxce auth login”).

5) Upload service hardening

  • Guard against nested dev‑workspace slugs to prevent recursive workspace nesting.
  • Enforce collection write ACLs on uploads when CTXCE_MCP_ACL_ENFORCE=1 and auth is enabled.
  • Initialize .codebase permissions and group for shared volumes.
  • Path Traversal hardening in upload_service

6) VS Code extension integration

  • Settings:
    • contextEngineUploader.mcpServerMode: bridge | direct.
    • contextEngineUploader.mcpTransportMode: sse-remote | http.
    • contextEngineUploader.autoStartMcpBridge: auto‑launch ctxce mcp-http-serve.
    • contextEngineUploader.mcpBridgePort, mcpBridgeBinPath, mcpBridgeLocalOnly.
  • MCP config writer:
    • bridge-stdio: single stdio MCP server via ctxce mcp-serve (behind SSE).
    • bridge-http: single HTTP MCP server via ctxce mcp-http-serve (auto‑start).
    • direct-sse/direct-http: two servers (indexer, memory) without bridge.
  • Guided sign‑in using ctxce auth commands; MCP config refresh/hot‑reload.

Configuration

Bridge CLI (env)

  • CTXCE_INDEXER_URL – MCP indexer URL (default http://localhost:8003/mcp).
  • CTXCE_MEMORY_URL – MCP memory URL (optional, default http://localhost:8002/mcp).
  • CTXCE_HTTP_PORT – HTTP bridge port (default 30810).
  • Resiliency:
    • CTXCE_TOOL_TIMEOUT_MSEC – per‑tool call timeout (default 300000).
    • CTXCE_TOOL_RETRY_ATTEMPTS – retry attempts (default 2).
    • CTXCE_TOOL_RETRY_DELAY_MSEC – delay between retries (default 200).
  • Logging/exit:
    • CTXCE_DEBUG_LOG – write bridge logs to file.
    • CTXCE_EXIT_ON_STDIN_CLOSE=1 – exit on stdio close.

Backend auth (env)

  • CTXCE_AUTH_ENABLED=1 – enable auth (default OFF).
  • CTXCE_AUTH_SHARED_TOKEN – shared token for /auth/login (token flow).
  • CTXCE_AUTH_ALLOW_OPEN_TOKEN_LOGIN – allow token login without shared token (dev only).
  • CTXCE_AUTH_ADMIN_TOKEN – required for /auth/users after bootstrap.
  • CTXCE_AUTH_DB_URL – SQLite path (default /work/.codebase/ctxce_auth.sqlite).
  • CTXCE_AUTH_SESSION_TTL_SECONDS – session TTL; <=0 disables expiry (default 0).
  • Collection ACLs:
    • CTXCE_ACL_ALLOW_ALL – bypass ACLs.
    • CTXCE_MCP_ACL_ENFORCE – enforce collection ACLs in MCP servers.
  • Bridge auth CLI:
    • CTXCE_AUTH_BACKEND_URL – upload service base URL.

Extension (typical)

{
  "contextEngineUploader.mcpServerMode": "bridge",
  "contextEngineUploader.mcpTransportMode": "http",
  "contextEngineUploader.autoStartMcpBridge": true,
  "contextEngineUploader.mcpBridgePort": 30810
}

voarsh added 10 commits December 8, 2025 07:16
Gets remove MCP tools and exposes as own, allows setting user workspace/customisation in outside of .env (and affect server in-process)
Enables the indexer to apply per-session defaults for collection, mode, and other parameters.

This change introduces a `set_session_defaults` tool to allow setting defaults that persist per connection. It also modifies `repo_search` to resolve collection and related hints from per-connection defaults, token-based defaults, and environment variables. It ensures that subsequent calls to the indexer within the same session will use these defaults, improving usability and reducing the need for repetitive parameter passing.
Adds support for proxying tools to a separate memory-based MCP server.

This allows the CLI to forward specific tool calls to a memory-based
context engine, enabling experimentation and local development without relying solely on the primary indexer. The `mcp-serve` command now accepts an optional `--memory-url` argument to configure the memory server.

It also improves CLI argument parsing, enabling a cleaner way to specify the workspace and indexer URL.
Removes the standalone indexer client as its functionality is now part of the mcp server.

This configuration supports scenarios where certain tools (e.g., those
beginning with "memory.") are specifically handled by the memory server, while others are directed to the main indexer.
Renames the package to align with the new naming
convention and avoid conflicts.

Adds a publish script to simplify the release process,
including authentication and version bumping.
Updates the publish workflow to reflect the renaming of the CLI package.
This ensures that the CLI is published correctly from the correct directory. Also adds `--provenance` flag to `npm publish`.
- add timeouts around indexer and memory listTools calls
- remove local ping tool and simplify tools/call proxying
- add optional debug logging via CTXCE_DEBUG_LOG
- avoid exceptions in tools/list logging that could hang refresh

Also upgrades the package version.
@voarsh2
Copy link
Contributor Author

voarsh2 commented Dec 9, 2025

I am now evaluating the approach - over making it a http service, separate from local stdio - since I encountered annoyances in how IDE clients manage stdio processes.......

voarsh added 16 commits December 9, 2025 04:18
- Extend ctx-mcp-bridge CLI with mcp-http-serve for HTTP-based MCP
- Share core bridge setup between stdio and HTTP transports
- Start ctxce HTTP bridge from the VS Code extension with workspace context
- Wire Claude/Windsurf MCP configs to bridge HTTP URL based on settings
- Keep existing stdio bridge behavior selectable via server/transport modes
Improves MCP configuration and management by introducing server modes ("bridge" and "direct") and clarifying transport modes ("sse-remote" and "http").

This change provides more flexibility in how MCP servers are wired, enabling both bridged and direct connections with different transport options. It also automates the startup of the HTTP bridge when necessary and refreshes MCP configs after the bridge is ready.
Addresses potential issues where the MCP bridge encounters session errors,
such as an expired or invalid session, by implementing a reinitialization
mechanism.

This ensures that the bridge attempts to re-establish connections to the remote MCP clients upon detecting a session-related error. This prevents the bridge from becoming unusable in cases where the underlying sessions expire or become invalidated.
Enhances the resilience of tool calls by adding retry logic for transient errors.

Introduces configurable retry attempts and delay via environment variables.
Also detects transient errors based on message content and error codes.

This change ensures that temporary network issues or service unavailability do not lead to immediate tool call failures, improving the overall stability of the system.
@voarsh2 voarsh2 changed the title MCP Bridge Wrapper: MCP Bridge (ctxce) + Optional Auth: single MCP server (HTTP/stdio) for Indexer & Memory, VS Code auto‑wiring, backend auth endpoints Dec 11, 2025
Remove /sse → /mcp rewrite from normalizeBridgeUrl
Update MCP URL defaults and bridge fallbacks to 8003/8002 /mcp HTTP endpoints
Ensure bridge modes consistently talk HTTP to the backend MCP pair; SSE remains for direct mcp-remote only
Treat empty strings for collection, mode, under, and language in set_session_defaults
as explicit unsets rather than no-ops. Update both per-connection and token-scoped
SESSION_DEFAULTS maps to remove those keys before applying any new defaults, so
sticky language/under/mode filters can be cleared without reconnecting.
Adds path remapping for tool results to use workspace-relative paths.

This change introduces a new module to handle the remapping of file paths returned by tools, specifically `repo_search`, `context_search`, and `context_answer`. It converts absolute or container paths to relative paths within the workspace, improving usability and portability of results.

It also introduces environment variables for diagnostics and path overriding.
@voarsh2 voarsh2 marked this pull request as ready for review December 12, 2025 13:56
@voarsh2 voarsh2 self-assigned this Dec 12, 2025
@voarsh2 voarsh2 marked this pull request as draft December 12, 2025 20:26
…rt breaks

- Fix /auth/login/password 500 by calling _ensure_db() in auth_backend.create_session() (was calling undefined _ensure_auth_db()).
- Harden scripts/mcp_auth.py fallback behavior: when CTXCE_AUTH_ENABLED=1 and auth_backend import fails, raise ValidationError instead of silently allowing all session/ACL checks.
Ensure in-process dense rerank (rerank_in_process) queries the request’s collection instead of falling back to COLLECTION_NAME.
Thread collection through rerank paths:
pass collection into rerank_in_process from mcp_indexer_server.repo_search
pass --collection to the rerank subprocess for consistency
Add regression tests to prevent cross-collection result leakage when rerank_enabled=true.
  - Add optional admin_ui imports with graceful fallback
  - Implement path traversal protection in delta bundle processing
  - Add missing contextlib import

  Prevents directory traversal attacks and improves service resilience when admin UI components are unavailable.
  - Add remapRelatedPathToClient function for better related_paths processing
  - Enhance remapHitPaths to handle nested related_paths per result
  - Update remapStringPath to support workspace-relative path overrides
  - Simplify payload processing by removing redundant code paths
  - Bump bridge package version to 0.0.8

  Improves path consistency between server and client workspaces with better
  relative path resolution and environment-based overrides.
@voarsh2
Copy link
Contributor Author

voarsh2 commented Dec 12, 2025

Doing last minute test fix (missing dep in test workflow) and a quick check then ready for merge.

Move process_delta_bundle/get_workspace_key into scripts/upload_delta_bundle so unit tests don’t need to import scripts/upload_service (and therefore don’t require fastapi in CI). Update upload_service to delegate to the new module and adjust traversal tests accordingly.
@voarsh2 voarsh2 marked this pull request as ready for review December 12, 2025 23:54
@m1rl0k m1rl0k merged commit e13cf0e into Context-Engine-AI:test Dec 13, 2025
1 check passed
m1rl0k added a commit that referenced this pull request Mar 1, 2026
MCP Bridge (ctxce) + Optional Auth: single MCP server (HTTP/stdio) for Indexer & Memory, VS Code auto‑wiring, backend auth endpoints
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants